#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: profile.py
@time: 2025/7/23  10:46
# @describe: 个人信息
"""
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from werkzeug.security import generate_password_hash
from utils.data_utils import load_users, save_users
import logging

profile_bp = Blueprint('profile', __name__)


@profile_bp.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')

        users = load_users()
        user_index = None
        current_user_data = None

        for i, user in enumerate(users):
            if user['id'] == current_user.id:
                user_index = i
                current_user_data = user
                break

        if not current_user_data:
            flash('用户数据不存在', 'error')
            return redirect(url_for('profile.profile'))

        updated = False

        # 更新用户名
        if username and username != current_user_data['username']:
            if any(u['username'] == username for u in users if u['id'] != current_user.id):
                flash('该用户名已被使用', 'error')
            else:
                current_user_data['username'] = username
                updated = True

        # 更新邮箱
        if email and email != current_user_data['email']:
            if any(u['email'] == email for u in users if u['id'] != current_user.id):
                flash('该邮箱已被使用', 'error')
            else:
                current_user_data['email'] = email
                updated = True

        # 更新密码
        if password and confirm_password:
            if password != confirm_password:
                flash('两次输入的密码不一致', 'error')
            else:
                current_user_data['password'] = generate_password_hash(password)
                updated = True

        # 保存更新
        if updated:
            users[user_index] = current_user_data
            try:
                save_users(users)
                flash('个人信息更新成功', 'success')
            except Exception as e:
                logging.error(f"保存用户数据失败: {e}")
                flash('保存失败，请稍后再试', 'error')

        return redirect(url_for('profile.profile'))

    # GET请求
    users = load_users()
    current_user_data = next((user for user in users if user['id'] == current_user.id), None)

    if not current_user_data:
        flash('无法加载用户数据', 'error')
        return redirect(url_for('index'))

    return render_template('user_profile.html', user=current_user_data)